$(document).ready(function() {
    reloadTree();
    loadUserTable();
    $('#reset').click();
   layui.use('form', function() {
        var form = layui.form;

        //监听提交
        form.on('submit(formDemo)', function(data) {
            let params = {};

            params.name = data.field.name;
            params.account = data.field.account;
            params.password = data.field.password;
            params.cellphone = data.field.cellphone;

            addUser(params)
            return false;
        });
    });

   /*日历插件*/
    layui.use('laydate', function() {
        var laydate = layui.laydate;
        //执行一个laydate实例
        laydate.render({
            elem: '#date-input',
            range: true,

        });
    });
})

var orgid = '';
var isPar = false;
var operate;
let prarms = {};
//用户表格
function loadUserTable() {
    if (prarms) {
        name = prarms.name;
        orgName = prarms.orgName;
        startTime = prarms.startTime;
        endTime = prarms.endTime;
    } else {
        var name = '';
        var orgName = '';
        var startTime = '';
        var endTime = '';
    }
    layui.use('table', function() {
        var table = layui.table;

        //第一个实例
        table.render({
            title: '',
            text: {
                none: '暂无数据'
            },
            elem: '#body-content-table',
            skin: 'nob',
            url: ajaxPrefix() + '/manage/user/list',
           headers: { SessionId: localStorage.getItem('sessionId') },
            where: {
                pageSize: 10,
                orgid:orgid,
                name:name,
                orgName:orgName,
                startTime:startTime,
                endTime:endTime
            },
            parseData: function(res) { //res 即为原始返回的数据
                return {
                    "code": res.status == 200 ? 0 : 1, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.result.total, //解析数据长度
                    "data": res.result.data //解析数据列表
                };
            },
            request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                    ,
                limitName: 'pageSize' //每页数据量的参数名，默认：limit
            },
            page: {
                limit: 10,
            } //开启分页
            ,
            cols: [
                [ //表头
                    {
                        field: 'name',
                        title: '用户名',
                        align: 'center'
                    }, {
                        field: 'account',
                        title: '账户',
                        align: 'center'
                    }, {
                        field: 'cellphone',
                        title: '联系方式',
                        align: 'center',
                    },{
                        field: 'orgName',
                        title: '组织名称',
                        align: 'center',
                    },{
                        field: 'dataTime',
                        title: '创建时间',
                        templet: function(d) {
                            return d.dataTime == undefined ? '暂无' : d.dataTime.substring(0, 19)
                        },
                        align: 'center'
                    }, {
                        field: 'status',
                        title: '状态',
                        align: 'center'
                    }, {
                        title: '操作',
                        align: 'center',
                        width: 120,
                        templet: function(d) {
                            let res = JSON.stringify(d);
                            return `<div>
                                        <div class="table-tool">
                                            <div onclick=initUpdate('${d.id}','${d.name}','${d.account}','${d.password}','${d.cellphone}')><button>修改</button></div>
                                            <div onclick=del('${d.id}')><button>删除</button></div>
                                        </div>
                                   </div>`;

                        },
                    },
                ]
            ]
        });
    });
}

function initUpdate(id,name,account,password,cellphone) {
            operate = id;
            $('.add-user>.main-tit>label').html('修改');
            $("#name").val(name);
            $("#account").val(account);
            $("#password").val(password);
            $("#cellphone").val(cellphone);
            $('.add-user').show();
}

function del(id) {
    var url = '/manage/user/delete?id='+id;
    layer.confirm('确定删除该用户吗?', {
        btn: ['确定', '取消']
    }, function(isConfirm) {
        Ajax(url, delUserCallBack);
        function delUserCallBack(result){
            layer.msg("删除成功");
            
            loadUserTable();
        }

    });
}

$('.layui-atn').click(function() {
    prarms.name = $('#username').val();
    prarms.orgName = $('#assname').val();
    let date = $('#date-input').val();
    prarms.startTime = date.substring(0, 10);
    prarms.endTime = date.substring(13, 23);
    loadUserTable(prarms);
})

/*树*/
var setting = {
    async: {
        autoParam: ["id"],
        enable: true,
        url: getAsyncUrl,
        type: "post",
        dataFilter: ajaxDataFilter,
        headers: { "SessionId": localStorage.getItem('sessionId') },
    },
    view: {
        expandSpeed: "fast",
        fontCss: getFont,
        showLine: true,
        dblClickExpand: false,
        showIcon: false
    },
    callback: {
        onAsyncSuccess: zTreeOnAsyncSuccess,
        onClick: zTreeOnClick,
        beforeExpand: beforeExpand,
        onExpand: onExpand
    },
    data: {
        key: {
            title: "name"
        },
        simpleData: {
            enable: true,
            idKey: "id",
            pIdKey: "pId"
        }
    }
};

var zNodes;

function reloadTree() {
    zTree = $.fn.zTree.init($("#treeDemo"), setting);
}

function getAsyncUrl(treeId, treeNode) {
    var url = ajaxPrefix() + "/manage/org";
    if (!treeNode) {
        url = url + "/tree_root";
    } else {
        url = url + "/tree_node";
    }

    return url;
}
//异步数据过滤
function ajaxDataFilter(treeId, parentNode, childNodes) {

    return childNodes;
}

//异步加载成功
function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
    if (!treeNode) { //根节点
        var rootNode = zTree.getNodesByParam("level", 0)[0];
        return;
    }

    var selTreeId = _selTreeId;
    if (!!selTreeId) {
        var selNode = zTree.getNodeByParam("id", selTreeId);
        if (!!selNode) {
            _selTreeId = null;
            zTree.selectNode(selNode);
            zTreeOnClick();
        }
    }
}
//获取选中的节点
function getSelectedNode() {
    var treeNode = zTree.getSelectedNodes();
    if (treeNode.length == 0) {

        return false;
    }
    return treeNode[0];
}

//刷新子节点并确定要选中节点ID
var _selTreeId = null;

function reloadNode(refreshId, isParent, selTreeId) {
    var node = zTree.getNodeByParam("id", refreshId);
    if (!!node && !!isParent) {
        node = node.getParentNode();
        if (!node) {
            _selTreeId = selTreeId;
            reloadTree();
            return;
        }
    }
    if (!!node) {
        _selTreeId = selTreeId;
        zTree.reAsyncChildNodes(node, "refresh");
    }
}


//右击事件
function getFont(treeId, node) {
    return node.font ? node.font : {};
}
//仅能打开一个子节点
var curExpandNode = null;

function beforeExpand(treeId, treeNode) {
    var pNode = curExpandNode ? curExpandNode.getParentNode() : null;
    var treeNodeP = treeNode.parentTId ? treeNode.getParentNode() : null;
    for (var i = 0, l = !treeNodeP ? 0 : treeNodeP.children.length; i < l; i++) {
        if (treeNode !== treeNodeP.children[i]) {
            zTree.expandNode(treeNodeP.children[i], false);
        }
    }
    while (pNode) {
        if (pNode === treeNode) {
            break;
        }
        pNode = pNode.getParentNode();
    }
    if (!pNode) {
        singlePath(treeNode);
    }

}

function singlePath(newNode) {
    if (newNode === curExpandNode) return;
    if (curExpandNode && curExpandNode.open == true) {
        var zTree = $.fn.zTree.getZTreeObj("treeDemo");
        if (newNode.parentTId === curExpandNode.parentTId) {
            zTree.expandNode(curExpandNode, false);
        } else {
            var newParents = [];
            while (newNode) {
                newNode = newNode.getParentNode();
                if (newNode === curExpandNode) {
                    newParents = null;
                    break;
                } else if (newNode) {
                    newParents.push(newNode);
                }
            }
            if (newParents != null) {
                var oldNode = curExpandNode;
                var oldParents = [];
                while (oldNode) {
                    oldNode = oldNode.getParentNode();
                    if (oldNode) {
                        oldParents.push(oldNode);
                    }
                }
                if (newParents.length > 0) {
                    zTree.expandNode(oldParents[Math.abs(oldParents.length - newParents.length) - 1], false);
                } else {
                    zTree.expandNode(oldParents[oldParents.length - 1], false);
                }
            }
        }
    }
    curExpandNode = newNode;
}

function onExpand(event, treeId, treeNode) {
    curExpandNode = treeNode;
}

//单击树节点事件
function zTreeOnClick(event, treeId, treeNode) {
    isPar = treeNode.isParent;
    if (treeNode.isParent) {
        orgid = treeNode.id;
        loadUserTable();
    }
}


$('.layui-btn').click(function() {
    if (!isPar) {
        layer.msg('请先在右侧选择所属组织')
    } else {
        $(":password").attr('required', true);
        $(":password").attr('lay-verify', 'required');
        operate = true;
        $('.add-user>.main-tit>label').html('新增');
        $('.add-user').show();
    }

})
$(".add-user>.main-tit>div").click(function() {
    $('.add-user').hide();
    $('#reset').click();
})

/*新增用户*/
addUser = (params) => {

    if (operate === true) {
        $.ajax({
            url: ajaxPrefix() + '/manage/user/checkUser?account=' + params.account,
            type: 'get',
            beforeSend: function(XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("SessionId", localStorage.getItem('sessionId'));
            },
            contentType: "application/json",
            success: function(res) {
                if (res.status != 200) {

                    layer.msg('账户已注册！', { icon: 7 })
                } else {
                    params.orgid = orgid;
                    $.ajax({
                        url: ajaxPrefix() + '/manage/user/add',
                        type: 'post',
                        data: JSON.stringify(params),
                        beforeSend: function(XMLHttpRequest) {
                            XMLHttpRequest.setRequestHeader("SessionId", localStorage.getItem('sessionId'));
                        },
                        contentType: "application/json",
                        success: function(res) {
                            if (res.status == 200) {
                                layer.msg('新增成功', { time: 1000 });
                                $(".add-user>.main-tit>div").click();
                                loadUserTable();
                            } else {
                                layer.msg('操作失败！', { time: 1000 })
                            }

                        }
                    });

                }

            }
        });
    } else {
        params.userId = operate;
        $.ajax({
            url: ajaxPrefix() + '/manage/user/update',
            type: 'post',
            data: JSON.stringify(params),
            beforeSend: function(XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("SessionId", localStorage.getItem('sessionId'));
            },
            contentType: "application/json",
            success: function(res) {
                if (res.status == 200) {
                    layer.msg('修改成功', { time: 1000 });
                    $(".add-user>.main-tit>div").click();
                    loadUserTable();
                } else {
                    layer.msg('操作失败！', { time: 1000 })
                }

            }
        });
}
}